package n_log

import (
	"fmt"
	"github.com/spf13/pflag"
	"go.uber.org/zap/zapcore"
	"strings"
)

const (
	FORAMT_CONSOLE = "console"
	FORAMT_JSON    = "json"
	OUTPUT_STD     = "stdout"
	OUTPUT_STD_ERR = "stderr"

	flagLevel = "log.level"
)

type Options struct {
	OutputPaths      []string `json:"output-paths" mapstructure:"output-paths"`
	ErrorOutputPaths []string `json:"error-output-paths" mapstructure:"error-output-paths"`
	Level            string   `json:"level" mapstructure:"level"`
	Format           string   `json:"format" mapstructure:"format"`
	Name             string   `json:"name" mapstructure:"name"`
}

type Option func(o *Options)

func NewOptions(opts ...Option) *Options {
	options := &Options{
		Level:            zapcore.DebugLevel.String(),
		Format:           FORAMT_CONSOLE,
		OutputPaths:      []string{OUTPUT_STD},     // 正确输出流
		ErrorOutputPaths: []string{OUTPUT_STD_ERR}, // 错误输出流
	}

	for _, opt := range opts {
		opt(options)
	}
	return options
}

func WithLevel(level string) Option {
	return func(o *Options) {
		o.Level = level
	}
}

// Validate 就可以自定义检测规则
func (o *Options) Validate() []error {
	var errs []error
	format := strings.ToLower(o.Format)
	if format != FORAMT_CONSOLE && format != FORAMT_JSON {
		errs = append(errs, fmt.Errorf("not suppor format %s", o.Level))
	}
	return errs
}

// AddFlags 可以自己将 options 具体的列映射到 flag 的字段上
func (o *Options) AddFlags(fs *pflag.FlagSet) {
	// StringVar(p *string, name string, value string, usage string)
	// p:修改的值 name:命令行参数的名称 value:默认值 usage:描述性字符串，用于解释此标志的作用
	fs.StringVar(&o.Level, flagLevel, o.Level, "log level")
}
